﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

public class LoadExample2 : MonoBehaviour
{

    public List<AssetReference> wallObjects;
    private bool _isAssetsReady = false;
    private int _toLoadCount;
    private int _charecterIndex = 0;
    void Start()
    {
        _toLoadCount = wallObjects.Count;
        foreach (var wallObject in wallObjects)
        {
            wallObject.LoadAssetAsync<GameObject>().Completed += OnCharacterAssetLoaded;
        }
    }

    private void OnCharacterAssetLoaded(AsyncOperationHandle<GameObject> asyncOperationHandle)
    {
        // 可以在这里操作已经成功加载的 GameObject asyncOperationHandle.Result
        Instantiate(asyncOperationHandle.Result);
        _toLoadCount--;
        if (_toLoadCount <= 0)
        {
            _isAssetsReady = true;
        }
    }
    
    // 在外部Button添加这个回调
    public void SpawnCharacter()
    {
        int index = Random.Range(0, wallObjects.Count);
        if (_isAssetsReady)
        {
            Vector3 position = Random.insideUnitSphere * 5;
            position.Set(position.x, 0, position.y);
            wallObjects[index].InstantiateAsync(position, Quaternion.identity);
        }
    }
    
    // Update is called once per frame
    void Update()
    {
        
    }
}
